package com.leen.user.service.impl;

import com.leen.common.vo.ResponseVO;
import com.leen.user.dto.YxUserDTO;
import com.leen.user.entity.YxUser;
import com.leen.user.repository.YxUserRepository;
import com.leen.user.service.YxUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * 分页查询
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class YxUserServiceImpl extends CrudServiceImpl<YxUser,Long> implements YxUserService {


    private  YxUserRepository yxUserRepository;

    @Autowired
    public void setYxUserRepository(YxUserRepository yxUserRepository) {
        this.yxUserRepository = yxUserRepository;
        super.setCrudRepository(yxUserRepository);
    }

    @Override
    public ResponseVO search(YxUserDTO yxUserDTO) {
        //分页查询
        Pageable pageable=PageRequest.of(yxUserDTO.getPageNumber()-1,yxUserDTO.getPageSize());
        //构建查询对象
        Specification<YxUser> specification=new Specification<YxUser>() {
            @Override
            public Predicate toPredicate(Root<YxUser> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list=new ArrayList<Predicate>();
                if (StringUtils.isNotBlank(yxUserDTO.getNickname())){
                    list.add(criteriaBuilder.like(root.get("username"),"%"+yxUserDTO.getNickname()+"%"));
                }
                if (StringUtils.isNotBlank(yxUserDTO.getPhone())){
                    list.add(criteriaBuilder.equal(root.get("phone"),yxUserDTO.getPhone()));
                }
                if (StringUtils.isNotBlank(yxUserDTO.getLoginType())){
                    list.add(criteriaBuilder.like(root.get("userType"),"%"+yxUserDTO.getLoginType()+"%"));
                }
                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        };
        //查询
        Page<YxUser> page = this.yxUserRepository.findAll(specification, pageable);

        return new ResponseVO(page.getTotalElements(),page.getContent());
    }
}
